<template>
    <div class="color-box table-form">
        <div class="table-title">
            <el-space>
                <el-button
                    type="primary"
                    style="width: 100%"
                    @click="onAddItem"
                    :disabled="isEditing"
                >
                    新增
                </el-button>
                <el-button
                    type="primary"
                    @click="copySelect"
                    :disabled="isEditing"
                    >复制所选</el-button
                >
                <el-button type="danger" @click="delAll" :disabled="isEditing"
                    >删除</el-button
                >
                <el-button
                    v-if="delType == 'designSpecifications1'"
                    type="warning"
                    :disabled="isEditing || signsTableData.length > 0"
                    @click.stop="copyDesignSpecifications"
                    >从设计规格复制</el-button
                >
                <el-button
                    v-if="delType == 'designSpecifications2'"
                    type="warning"
                    :disabled="isEditing || signsTableData.length > 0"
                    @click.stop="copyDesignSpecifications"
                    >从产品规格复制</el-button
                >
            </el-space>
        </div>
        <el-table
            :data="signsTableData"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            border
            :row-class-name="tableRowClassName"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column
                prop="accessoryName"
                label="配件名称"
                width="160px"
            >
                <template #default="scope">
                    <el-select
                        v-model="scope.row.accessoryName"
                        placeholder="请选择"
                        :disabled="isEditing"
                        clearable
                        filterable
                        remote
                        :remote-method="
                            (keyword) => {
                                remoteMethodAccessoryName(keyword, scope.row);
                            }
                        "
                    >
                        <el-option
                            v-for="item in selfParts"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="position" label="位置" width="120">
                <template #default="scope">
                    <el-select
                        v-model="scope.row.position"
                        placeholder="请选择"
                        :disabled="isEditing"
                        clearable
                        filterable
                        remote
                        :remote-method="
                            (keyword) => {
                                remoteMethodPosition(keyword, scope.row);
                            }
                        "
                    >
                        <el-option
                            v-for="item in props.dictOptions.position"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="workmanship" label="工艺" width="160">
                <template #default="scope">
                    <el-select
                        v-model="scope.row.workmanship"
                        placeholder="请选择"
                        :disabled="isEditing"
                        @change="workmanshipChange(scope.row)"
                        clearable
                        filterable
                        remote
                        :remote-method="
                            (keyword) => {
                                remoteMethodWorkmanship(keyword, scope.row);
                            }
                        "
                    >
                        <el-option
                            v-for="item in props.dictOptions.workmanship"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="workmanshipColor" label="工艺做色">
                <template #default="scope">
                    <div style="display: flex; align-items: center">
                        <input
                            :maxlength="500"
                            v-model="scope.row.workmanshipColor"
                            placeholder="请输入"
                            :disabled="isEditing"
                        />
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="workmanshipType" label="新旧" width="100">
                <template #default="scope">
                    <el-select
                        v-model="scope.row.workmanshipType"
                        placeholder="请选择"
                        :disabled="isEditing"
                        @change="workmanshipChange(scope.row)"
                    >
                        <el-option
                            v-for="item in props.dictOptions.newOrOld"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="signNum" label="标志\图案编号">
                <template #default="scope">
                    <div style="display: flex; align-items: center">
                        <input
                            v-if="scope.row.workmanshipType == 'New'"
                            :maxlength="40"
                            v-model="scope.row.signNum"
                            disabled
                            placeholder=""
                        />
                        <input
                            v-else
                            :maxlength="40"
                            v-model="scope.row.signNum"
                            :disabled="isEditing"
                            placeholder=""
                        />
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="size" label="尺码" width="160px">
                <template #default="scope">
                    <div :class="['size-row',{'isEditing':isEditing}]" @click="showColorSelect(scope.row, $index)">
                        <span v-for="(s, i) in scope.row.size.split(',')">
                            {{ s
                            }}{{
                                i == scope.row.size.split(",").length - 1
                                    ? ""
                                    : ","
                            }}
                        </span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="color" label="颜色">
                <template #default="scope">
                    <el-input
                        type="textarea"
                        @click="showColorSelect(scope.row, $index)"
                        @focus="changeFocus($event)"
                        v-model="scope.row.color"
                        :autosize="{ minRows: 1, maxRows: 4 }"
                        :disabled="isEditing"
                    />
                </template>
            </el-table-column>
            <!-- <el-table-column
                prop="op"
                label="操作"
                width="70"
            >
                <template #default="{ row, $index }">
                    <el-button
                        type="danger"
                        size="small"
                        @click.prevent="deleteRow($index)"
                    >
                        <el-icon>
                            <Delete />
                        </el-icon>
                    </el-button>
                </template>
            </el-table-column> -->
        </el-table>

        <!-- 颜色选择弹窗 -->
        <el-dialog
            v-model="showColorSelectDialog"
            destroy-on-close
            width="50%"
            title="颜色选择"
        >
            <div>
                <el-checkbox
                    v-model="checkAllsize"
                    @change="handleCheckAllChangeSize"
                    >全选尺码</el-checkbox
                >
                <div style="margin: 5px 0"></div>
                <el-checkbox-group
                    v-model="checkedSize"
                    @change="handleCheckedSizeChange"
                >
                    <el-checkbox
                        v-for="item in props.sizeData"
                        :label="item.sizeNum"
                        :key="item.sizeNum"
                        >{{ item.sizeNum }}</el-checkbox
                    >
                </el-checkbox-group>
            </div>
            <el-checkbox v-model="checkAll" @change="handleCheckAllChange"
                >全选颜色</el-checkbox
            >
            <div style="margin: 5px 0"></div>
            <el-checkbox-group
                v-model="checkedColor"
                @change="handleCheckedColorChange"
            >
                <el-checkbox
                    v-for="item in props.colorData"
                    :label="item.colorNum"
                    :key="item.colorNum"
                    >{{ item.colorNum }}</el-checkbox
                >
            </el-checkbox-group>
            <template #footer>
                <div class="dialog-footer">
                    <!-- <el-button type="primary" @click="save('1', 'edit')"
                        >确定</el-button
                    > -->
                    <el-button type="primary" @click="saveChange()"
                        >确定</el-button
                    >
                    <el-button @click="showColorSelectDialog = false"
                        >取消</el-button
                    >
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { useDict } from "@/utils/dictionary.js";
import { emitter } from "@/utils/bus.js";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { generateWorkingProcedureNumber } from "@/api/plmProductSpec.js";
import {
    ref,
    reactive,
    onMounted,
    defineProps,
    defineExpose,
    watch,
} from "vue";
import { deepClone2, debounce } from "@/utils/tool.js";

const router = new useRouter();
const route = new useRoute();

defineOptions({
    name: "designSpecifications",
});

const props = defineProps({
    selfParts: { type: Array, default: [] },
    treeDataOne: { type: Array, default: [] },
    colorData: { type: Array, default: [] },
    sizeData: { type: Array, default: [] },
    dictOptions: { type: Object, defaul: {} },
    delType: {
        type: String,
        default: "",
    },
    isEditing: { type: Boolean, default: false },
});
const emit = defineEmits(["copyDesignSpecifications"]);

// 配件名称-自动选择
const remoteMethodAccessoryName = (name, row) => {
    let index = props.selfParts.findIndex((item) => {
        return item.value == name;
    });
    if (index != -1) {
        row.accessoryName = props.selfParts[index].value;
    }
};
// 位置-自动选择
const remoteMethodPosition = (name, row) => {
    let index = props.dictOptions.position.findIndex((item) => {
        return item.value == name;
    });
    if (index != -1) {
        row.position = props.dictOptions.position[index].value;
    }
};
// 工艺-自动选择
const remoteMethodWorkmanship = (name, row) => {
    let index = props.dictOptions.workmanship.findIndex((item) => {
        return item.value == name;
    });
    if (index != -1) {
        row.workmanship = props.dictOptions.workmanship[index].value;
        workmanshipChange(row);
    }
};

const signsTableData = ref([]); // 表格数据

// 尺码新增一行
const onAddItem = () => {
    let item = {
        accessoryName: "", // 配件名称
        position: "", // 位置
        workmanship: "", // 工艺
        workmanshipType: "", // 工艺新旧
        workmanshipColor: "", // 工艺做色
        signNum: "", // 标志/图案编号
        size: "", // 尺码
        color: "", // 颜色
    };
    if (props.sizeData.length == 1 && props.colorData.length == 1) {
        item["size"] = props.sizeData[0].sizeNum;
        item["color"] = props.colorData[0].colorNum;
    }
    signsTableData.value.push(item);
};
//尺码删除一行
const deleteRow = (index) => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        signsTableData.value.splice(index, 1);
    });
};
// 批量操作
const multipleSelection = ref([]);
const selectlistRow = ref([]);
const tableRowClassName = (row, index) => {
    row.row.index = row.rowIndex;
};
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
    selectlistRow.value = val;
};
const delAll = () => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let list = signsTableData.value;
        multipleSelection.value.forEach((item) => {
            list = list.filter((items) => items.index !== item.index);
        });
        signsTableData.value = list;
    });
};

// 复制所选
const copySelect = () => {
    let list = signsTableData.value;
    let copylist = [];
    list.forEach((item) => {
        let index = multipleSelection.value.findIndex((v) => {
            return v.index == item.index;
        });
        if (index != -1) {
            let itemCopy = Object.assign({}, item);
            if (itemCopy.ID) delete itemCopy.ID;
            if(itemCopy.workmanshipType && itemCopy.workmanshipType == 'New'){
                itemCopy.workmanshipType = 'Old'
            }
            copylist.push(itemCopy);
        }
        return index != -1;
    });
    let ll = list.concat(copylist);
    signsTableData.value = deepClone2(ll);
};

const updateSignsData = (val) => {
    signsTableData.value = val;
};

// 颜色弹窗
const checkAll = ref(true);
const checkedColor = ref([]); // 所选颜色
const checkAllsize = ref(true);
const checkedSize = ref([]); // 所选尺码

// 颜色选择
const showColorSelectDialog = ref(false);
const currentRow = ref({});
const showColorSelect = (row) => {
    if(props.isEditing) return
    checkedColor.value = [];
    showColorSelectDialog.value = true;
    currentRow.value = row;
    checkedColor.value = !!row.color ? row.color.split(",") : [];
    checkedSize.value = !!row.size ? row.size.split(",") : [];
    if (
        checkedColor.value.length != 0 &&
        checkedColor.value.length == props.colorData.length
    ) {
        checkAll.value = true;
    } else {
        checkAll.value = false;
    }
    if (
        checkedSize.value.length != 0 &&
        checkedSize.value.length == props.sizeData.length
    ) {
        checkAllsize.value = true;
    } else {
        checkAllsize.value = false;
    }
};
const changeFocus = ($event) => {
    $event.target.blur();
};
const handleCheckAllChange = (val) => {
    let colors = props.colorData.map((res) => {
        return res.colorNum;
    });
    checkedColor.value = val ? colors : [];
};
const handleCheckAllChangeSize = (val) => {
    let size = props.sizeData.map((res) => {
        return res.sizeNum;
    });
    checkedSize.value = val ? size : [];
};
// 颜色选择
const handleCheckedColorChange = (val) => {
    if (
        checkedColor.value.length != 0 &&
        checkedColor.value.length == props.colorData.length
    ) {
        checkAll.value = true;
    } else {
        checkAll.value = false;
    }
};

// 尺码选择
const handleCheckedSizeChange = () => {
    if (
        checkedSize.value.length != 0 &&
        checkedSize.value.length == props.sizeData.length
    ) {
        checkAllsize.value = true;
    } else {
        checkAllsize.value = false;
    }
};

// 确定
const saveChange = () => {
    checkedColor.value.sort((a, b) => {
        return a.localeCompare(b);
    });
    currentRow.value.color = checkedColor.value.join(",");
    currentRow.value.size = checkedSize.value.join(",");
    showColorSelectDialog.value = false;
};

// 颜色改变同步改变
const colorChangeFun = (colorChangeVal) => {
    let list = signsTableData.value;
    let allColors = [];
    for (let key in colorChangeVal) {
        if (!!colorChangeVal[key]) {
            allColors.push(colorChangeVal[key]);
        }
    }
    console.log(allColors);
    list.forEach((item) => {
        let colors = !!item.color ? item.color.split(",") : [];
        for (let i = colors.length - 1; i >= 0; i--) {
            if (colorChangeVal[colors[i]]) {
                colors[i] = colorChangeVal[[colors[i]]];
            } else {
                colors.splice(i, 1);
            }
        }
        item["color"] = colors.join(",");
        // let colors1 = colors.filter((c) => {
        //     return allColors.includes(c);
        // });
        // item["color"] = colors1.join(",");
    });
    signsTableData.value = list;
};

// 复制
const copyDesignSpecifications = () => {
    emit("copyDesignSpecifications", props.delType);
};

// 工艺改变
// const generateWorkingProcedureNumberOldObj = ref({})
const workmanshipChange = (row) => {
    row["signNum"] = "";
    if (row.workmanshipType == "New" && row.workmanship) {
        let params = {
            workmanship: row.workmanship,
        };
        generateWorkingProcedureNumber(params).then((res) => {
            if (res.code == 0) {
                row["signNum"] = res.data;
            }
        });
    }
};

watch(
    () => props.selfParts,
    () => {
        for (let i = signsTableData.value?.length - 1; i >= 0; i--) {
            let item = signsTableData.value[i];
            if (!!item.accessoryName) {
                let index = props.selfParts.findIndex((val) => {
                    return val.value == item.accessoryName;
                });
                if (index == -1) {
                    // item["accessoryName"] = "";
                    let list = signsTableData.value;
                    signsTableData.value.splice(i, 1);
                }
            }
        }
        // signsTableData.value.forEach((item, index) => {
        //     if(!!item.accessoryName){
        //         let i = props.selfParts.findIndex((val) => {
        //             return val.value == item.accessoryName;
        //         });
        //         if (i == -1) {
        //             // item["accessoryName"] = "";
        //             let list = signsTableData.value;
        //             signsTableData.value.splice(index, 1);
        //         }
        //     }
        // });
    }
);

defineExpose({ signsTableData, colorChangeFun, updateSignsData });

onMounted(async () => {
    // 修改尺码，所关联值同步修改
    emitter.on("sizeChangeFun", (sizeChangeVal) => {
        // debugger
        let list = deepClone2(signsTableData.value);
        if (sizeChangeVal.type == "edit") {
            list.forEach((item) => {
                let sizes = !!item.size ? item.size.split(",") : [];
                let index = sizes.findIndex((res) => {
                    return res == sizeChangeVal.sizeOld;
                });
                if (index != -1) {
                    sizes[index] = sizeChangeVal.sizeNew;
                }
                item.size = sizes.join(",");
            });
        } else if (sizeChangeVal.type == "del") {
            list.forEach((item) => {
                let sizes = !!item.size ? item.size.split(",") : [];
                sizes = sizes.filter((res) => {
                    return res != sizeChangeVal.sizeOld;
                });
                item.size = sizes.join(",");
            });
        }
        signsTableData.value = list;
    });
});
</script>

<style lang="scss" scoped>
.table-form {
    .el-form-item {
        margin-bottom: 0;
        width: 80%;
    }
}
:deep(.el-table__header) {
    width: 100% !important;
}
.size-row {
    border: 1px solid var(--el-border-color);
    min-height: 31px;
    padding: 0px 2px;
    border-radius: 4px;
    display: flex;
    flex-wrap: wrap;
    line-height: 18px;
}
.isEditing{
    background: var(--el-disabled-bg-color);
}
input {
    --el-input-inner-height: calc(var(--el-input-height, 32px) - 2px);
    // min-height: 24px;
    width: 100%;
    flex-grow: 1;
    -webkit-appearance: none;
    color: var(--el-input-text-color, var(--el-text-color-regular));
    font-size: inherit;
    height: var(--el-input-inner-height);
    line-height: var(--el-input-inner-height);
    padding: 0;
    outline: none;
    border: solid 1px #ddd;
    background: none;
    background-color: #fff; /* 背景色 */
    box-sizing: border-box;

    background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    background-image: none;
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    cursor: text;
    transition: var(--el-transition-box-shadow);
    transform: translate3d(0, 0, 0);
    // box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color))
    //     inset;
}
input:disabled {
    background-color: var(--el-disabled-bg-color);
    // box-shadow: 0 0 0 1px var(--el-disabled-border-color) inset;
}
select:disabled {
    background-color: var(--el-disabled-bg-color);
    // box-shadow: 0 0 0 1px var(--el-disabled-border-color) inset;
}
</style>